using System;
using Firestarter.DB.Schema.BO;
using FireStarterModeller.BO;
using Habanero.Util;

namespace Firestarter.DB_DomainModel.Logic
{
    public class DBToDMPropertyUpdater : IDBToDMPropertyUpdater
    {
        public IDBTypeToDMPropertyTypeMapper DBTypeToDMPropertyTypeMapper { get; private set; }

        public DBToDMPropertyUpdater(IDBTypeToDMPropertyTypeMapper typeMapper)
        {
            if (typeMapper == null) throw new ArgumentNullException("typeMapper");
            DBTypeToDMPropertyTypeMapper = typeMapper;
        }

        public void UpdateValues(IDBColumn fromDBColumn, DMProperty toDMProperty)
        {
            if(string.IsNullOrEmpty(toDMProperty.PropertyName)) toDMProperty.PropertyName = PascalCaseFieldName(fromDBColumn.ColumnName.Trim());
            toDMProperty.PropertyType = DBTypeToDMPropertyTypeMapper.GetDMPropertyType(fromDBColumn.DataType, fromDBColumn.DataLength);
            if(string.IsNullOrEmpty(toDMProperty.Description)) toDMProperty.Description = fromDBColumn.Comment;
            toDMProperty.Compulsory = !fromDBColumn.Nullable.GetValueOrDefault(true);
            toDMProperty.AutoIncrementing = fromDBColumn.IsAutoIncrementing.GetValueOrDefault(false);
            if (!toDMProperty.KeepValuePrivate.GetValueOrDefault()) toDMProperty.KeepValuePrivate = NameContainsPassword(fromDBColumn);
            if (toDMProperty.OrdinalPosition == null) toDMProperty.OrdinalPosition = fromDBColumn.OrdinalPosition;

            DMPropertyType propertyType = toDMProperty.PropertyType;
            if (propertyType != null && propertyType.PropertyTypeFullName == "System.String")
            {
                DMPropRuleParameter maxLengthParameter =
                    toDMProperty.DefaultPropRule.PropRuleParameters.Find(parameter => parameter.KeyName == "maxLength");
                if (maxLengthParameter != null)
                {
                    if (fromDBColumn.DataLength < 0) fromDBColumn.DataLength = 500;
                    if (fromDBColumn.DataLength == null) maxLengthParameter.Value = "50";
                    maxLengthParameter.Value = fromDBColumn.DataLength.ToString();
                }
            }
        }

        private static bool NameContainsPassword(IDBColumn dbColumn)
        {
            return dbColumn.ColumnName.ToUpper().Contains("PASSWORD");
        }

        private static string PascalCaseFieldName(string fieldNameConverted)
        {
            return StringUtilities.PascalCaseTableName(fieldNameConverted.Trim());
        }
    }
}